import { getAsyncRoutes } from "@/api/routes";
import router, { constantRoutes } from "@/router";
import { store } from "@/store";
import { defineStore } from "pinia";
import { ref } from "vue";
import { type RouteRecordRaw } from "vue-router";

const ManageLayout = () => import("@/layouts/manage/index.vue");
const PortalLayout = () => import("@/layouts/portal/index.vue");
const modules = import.meta.glob("@/views/**/*.vue");

export const usePermissionStore = defineStore(
  "permission-store",
  () => {
    /** 整体路由生成的菜单（静态、动态） */
    const wholeMenus = ref<RouteRecordRaw[]>([]);
    /** 动态生成的路由菜单 */
    const asyncMenus = ref<RouteRecordRaw[]>([]);
    // 大屏菜单
    const portalMenus = ref<RouteRecordRaw[]>([]);
    // 后台管理菜单
    const manageMenus = ref<RouteRecordRaw[]>([]);
    /** 组装整体路由生成的菜单 */
    const handleWholeMenus = (routes: RouteRecordRaw[]) => {
      wholeMenus.value = constantRoutes.concat(routes);
    };

    /** 获取后端传来的动态路由并处理 */
    const getMenuRouter = () => {
      return new Promise((resolve, reject) => {
        getAsyncRoutes()
          .then((res) => {
            const routes = res.data.data || [];
            if (routes.length === 0) {
              asyncMenus.value = [];
              handleWholeMenus(routes);
              resolve(routes);
            } else {
              const portal = routes.filter((i: any) => i.code === "portal");
              const manage = routes.filter((i: any) => i.code === "manage");
              if (portal.length) portalMenus.value = newAsyncRoutes(portal[0].children, "portal");
              if (manage.length) manageMenus.value = newAsyncRoutes(manage[0].children, "manage");
              if (manageMenus.value && manageMenus.value.length) {
                // tags标签固定第一个菜单
                manageMenus.value[0].children[0].meta.affix = true;
                manageMenus.value.forEach((v: RouteRecordRaw) => {
                  router.addRoute(v);
                });
              }
              if (portalMenus.value && portalMenus.value.length) {
                portalMenus.value.forEach((v: RouteRecordRaw) => {
                  router.addRoute(v);
                });
              }
              if (!portalMenus.value.length && !manageMenus.value.length) return;
              if (portalMenus.value?.length) {
                router.addRoute({
                  path: "/",
                  redirect: portalMenus.value[0].path
                });
              } else if (manageMenus.value?.length) {
                router.addRoute({
                  path: "/",
                  redirect: manageMenus.value[0].path
                });
              }
              if (!router.hasRoute("pathMatch")) {
                router.addRoute({
                  path: "/:pathMatch(.*)",
                  name: "pathMatch",
                  redirect: "/404"
                });
              }

              asyncMenus.value = [...portalMenus.value, ...manageMenus.value];

              handleWholeMenus(asyncMenus.value as any);
              resolve(routes);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    };
    /** 获取要展示的菜单列表 */
    const newAsyncRoutes = (routeList: any, type: string) => {
      const newRoutes = [] as any;
      // 如果没有权限菜单就结束
      if (!routeList || !routeList.length) return;
      routeList.forEach((v: any) => {
        if (!v.isHidden && v.type !== "3") {
          const hasChild = v?.children && v.children.length;
          const routerChild = !hasChild
            ? [
                {
                  path: v.url,
                  meta: { title: v.name, icon: v.icon },
                  component: modules[`/src/views/${type}${v.url}.vue`]
                }
              ]
            : v.children.map((item: any) => {
                return {
                  path: item.url,
                  meta: { title: item.name, icon: item.icon },
                  component: modules[`/src/views/${type}${item.url}.vue`]
                };
              });
          newRoutes.push({
            path: hasChild ? v.url : `/${v.code}`,
            component: type === "portal" ? PortalLayout : ManageLayout,
            name: v.code,
            meta: { title: v.name, icon: v.icon },
            children: routerChild,
            redirect: (() => {
              if (hasChild) {
                return routerChild[0].path;
              } else {
                return v.url;
              }
            })()
          });
        }
      });
      return newRoutes;
    };

    return { wholeMenus, asyncMenus, portalMenus, manageMenus, getMenuRouter, handleWholeMenus };
  },
  {
    persist: {
      paths: ["asyncMenus", "wholeMenus", "manageMenus", "portalMenus"]
    }
  }
);
/** 在 setup 外使用 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
